# import inline as inline
# import pandas as pd
# import shutil
# import os
# from rdkit import Chem
from rdkit.Chem import AllChem
# from rdkit import DataStructs
# import json
import re
from rdkit import Chem
# from rdkit.Chem import Draw


# 单例模式

def singleton(cls):
    # 创建一个字典用来保存类的实例对象
    _instance = {}

    def _singleton(*args):
        # 先判断这个类有没有对象
        if cls not in _instance:
            #   没有则 创建一个对象,并保存到字典当中
            _instance[cls] = cls(*args)

            # 有 则 将实例对象返回
        return _instance[cls]

    return _singleton



@singleton
class File(object):
    doi_aff_dict = {}  # key 为 doi，value 为 [aff],aff 就是机构的英文名称
    with open("reaxys-doi-aff.csv", "r", encoding="utf-8") as f:  # doi	affid	aff
        line = f.readline()
        while line:
            line = line.replace("\n", "")
            items = re.split("\t", line)
            doi = items[0]
            aff = items[2]
            if len(items) == 3:
                if doi in doi_aff_dict:
                    doi_aff_dict[doi].append(aff)
                else:
                    doi_aff_dict[doi] = [aff]
            line = f.readline()

    XRN_smiles_dict = {}  # key 为 XRN，value 为 smiles
    with open("athepharm-property-short.csv", "r",
              encoding="utf-8") as f:  # 是athepharm-property.csv全量数据文件抽取XRN与smiles两个字段产生
        line = f.readline()
        while line:
            line = line.replace("\n", "")
            items = re.split(",", line)
            if len(items) == 2:
                XRN = items[0]
                smiles = items[1]
                XRN_smiles_dict[XRN] = smiles
            line = f.readline()

    en_cn_dict = {}  # key为机构英文名称，value为中文名称
    # 这个文件是通过organization_dictionary_temp，organization_aff等文件整理得出两列，一列机构英文名称，一列机构中文名称
    with open("address.csv", "r", encoding="utf-8") as f:
        line = f.readline()
        while line:
            line = line.replace("\n", "")
            items = re.split("\t", line)
            if len(items) == 2:
                en = items[0]
                cn = items[1]
                en_cn_dict[en] = cn
            line = f.readline()

    smiles_org_dict = {}  # key 为smiles，value 为[org]
    with open("China-reaxys-XRN-dois.csv", "r",
              encoding="utf-8") as f:  # XRN dois
        line = f.readline()

        while line:
            line = line.replace("\n", "")
            items = re.split("\t", line)
            if len(items) == 2:
                XRN = items[0]
                if XRN in XRN_smiles_dict:
                    smiles = XRN_smiles_dict[XRN]
                    if smiles in smiles_org_dict:
                        substance_list = smiles_org_dict[smiles]
                    else:
                        substance_list = []
                        smiles_org_dict[smiles] = substance_list
                    dois = items[1]
                    doi_list = re.split("¶", dois)
                    for doi in doi_list:
                        if doi in doi_aff_dict:
                            affs = doi_aff_dict[doi]
                            for aff in affs:
                                org_item = {}
                                cn = ""
                                if aff in en_cn_dict:
                                    cn = en_cn_dict[aff]
                                org_item["en"] = aff
                                org_item["cn"] = cn
                                substance_list.append(org_item)

            line = f.readline()

    radius = 5  # 考虑半径为5，
    fingerprint_dict = {}  # key 为smiles value 为 fingerprint
    for smiles in smiles_org_dict:
        molecular = Chem.MolFromSmiles(smiles)
        try:
            fingerprint = AllChem.GetMorganFingerprintAsBitVect(molecular, radius, nBits=1024)  # 指纹长度为1024
            fingerprint_dict[smiles] = fingerprint
        except Exception as e:  # 这里出现异常原因是从athepharm-property.csv全量数据文件抽取smiles字段并没有进行rdkit 检验
            print(smiles)


# % matplotlib
# inline
# import matplotlib.pyplot as plt
# import ipywidgets as widgets  # 控件库
# from IPython.display import display  # 显示控件的方法
import time

from rdkit import Chem, DataStructs
from rdkit.Chem import AllChem



def get_sim(sender):
    file = File()
    target = sender.split(',')

    print(target)

    num = 100  # 每个目标smiles返回前多少个相似物

    count = 1
    now = int(round(time.time() * 1000))
    now_str = time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime(now / 1000))
    for target_smiles in target:
        result = []
        mols = []
        legs = []
        result_item = {}
        result.append(result_item)
        result_item["smiles"] = target_smiles
        target_mol = Chem.MolFromSmiles(target_smiles)

        substance = []
        result_item["substance"] = substance
        similarity_dict = {}  # key 为smiles，value为 similarity
        try:
            target_molecular = Chem.MolFromSmiles(target_smiles)
            target_fingerprint = AllChem.GetMorganFingerprintAsBitVect(target_molecular, file.radius, nBits=1024)
            for smiles in file.fingerprint_dict:
                fingerprint = file.fingerprint_dict[smiles]
                similarity = DataStructs.TanimotoSimilarity(target_fingerprint, fingerprint)
                similarity_dict[smiles] = similarity
        except Exception as e:
            # print(target_smiles)
            print()
        similarity_list = sorted(similarity_dict.items(), key=lambda x: x[1], reverse=True)  # 相似性降序排列

        return similarity_list

        # ct = 1
        # for smiles_item in similarity_list[:num]:
        #     item = {}
        #     item["smiles"] = smiles_item[0]  # smiles
        #     mol = Chem.MolFromSmiles(item["smiles"])
        #     legs.append(str(ct))
        #     mols.append(target_mol)
        #     mols.append(mol)
        #     item["similarity"] = smiles_item[1]  # similarity
        #     item["org_links"] = smiles_org_dict[smiles_item[0]]  # smiles 对应的机构信息
        #     orgs = '\n'.join([i['en'] for i in item['org_links']])
        #     substance.append(item)
        #
        #
        #     legs.append(str(item["smiles"])
        #                 + '\n' + str(item["similarity"])
        #                 + '\n' + orgs
        #                 )
        #     ct += 1

        # img = Draw.MolsToGridImage(
        #     mols,
        #     molsPerRow=2,
        #     subImgSize=(1000, 1000),
        #     legends=[x for x in legs],
        #     returnPNG=False
        # )
        #
        # img.save(now_str + '-' + str(count) + '.jpg')
        #
        # with open(now_str + '-' + str(count) + ".json", "w", encoding="utf-8") as f:
        #     result_str = json.dumps(result, ensure_ascii=False)
        #     f.write(result_str)
        #
        # count += 1
    #     plt.figure(figsize=(200,200))
    #     plt.xlim(0,2000)
    #     plt.ylim(10000,0)
    #     plt.imshow(img)

    #     plt.show()

# text = widgets.Text()
# display(text)

# target = [  # 目标物列表
#         "N#CCC(=O)C1CCCC1"
#     ]


# text.on_submit(get_sim)

